﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;
using Medicine.Fragments;
using static Android.Views.View;

namespace Medicine.Activities
{
    [Activity(Label = "增加药品信息")]
    public class InsertActivity : AppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.InsertLayout);

            InitEvent();
        }

        /// <summary>
        /// 绑定事件
        /// </summary>
        private void InitEvent()
        {
            Button button = FindViewById<Button>(Resource.Id.Btn_Submit);
            button.Click += (s, e) => SaveData();

            TextInputEditText dateTxt = FindViewById<TextInputEditText>(Resource.Id.Txt_ExpirationDate);
            dateTxt.FocusChange += DateSelect_OnClick;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        protected virtual void SaveData()
        {
            var data = InitData();

            var msg = data.CheckData();
            if(msg.Result== Models.NoticeEnum.Failed)
            {
                Helpers.MessageShow.ShowNoticeMsg(this,
                                                    "保存失败提示",
                                                    msg.Message);
                return;
            }

            var hasData = DbContext.DbC.FirstQuery<Models.Medicine>(s => s.MedicineName == data.MedicineName);
            if (hasData != null && !string.IsNullOrEmpty(hasData.Id))
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                builder.SetMessage($"药品名称{data.MedicineName}已记录是否继续添加？");
                builder.SetTitle("重复添加提示");

                builder.SetPositiveButton("确定", new EventHandler<DialogClickEventArgs>((s, e) =>
                {
                    SaveData(data);
                }));

                builder.SetNegativeButton("取消", new EventHandler<DialogClickEventArgs>((s, e) =>
                {

                }));

                builder.Create().Show();
            }
            else
                SaveData(data);
        }

        private void SaveData(Models.Medicine medicine)
        {
            var result = DbContext.DbC.InsertByBaseModel(medicine);
            if (result > 0)
            {
                Helpers.MessageShow.ShowShortMsg(this, "保存成功");
                System.Threading.Tasks.Task.Delay(2000);
                this.Finish();
            }
            else
                Helpers.MessageShow.ShowShortMsg(this, "保存失败");
        }

        /// <summary>
        /// 自动建立将要保存的数据
        /// </summary>
        /// <returns></returns>
        protected Models.Medicine InitData()
        {
            var data = new Models.Medicine();
            var properties = data.GetType().GetProperties();
            var resource = typeof(Resource.Id);
            var t = resource.GetFields();
            foreach (var item in properties)
            {
                var txtName = $"Txt_{item.Name}";
                var txtResource = t.FirstOrDefault(s => s.Name == txtName);
                if (txtResource == null)
                    continue;
                var tmpObj = resource.Assembly.CreateInstance(txtResource.ReflectedType.Name);
                var txtId = txtResource.GetValue(tmpObj);
                if (txtId != null)
                {
                    int tmpTxtId = Convert.ToInt32(txtId);
                    //时间或日期格式特殊处理
                    if (item.Name.Contains("Time") || item.Name.Contains("Date"))
                    {
                        EditText dateTxt = FindViewById<EditText>(tmpTxtId);
                        if (dateTxt != null)
                        {
                            var v = Convert.ToDateTime(dateTxt.Text);
                            item.SetValue(data, v);
                        }
                        continue;
                    }

                    TextInputEditText txt = FindViewById<TextInputEditText>(tmpTxtId);
                    if (txt != null)
                    {
                        item.SetValue(data, txt.Text);
                    }
                }
                //TextInputEditText txt = FindViewById<TextInputEditText>();
            }
            return data;
        }

        /// <summary>
        /// 选择日期绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DateSelect_OnClick(object sender, FocusChangeEventArgs e)
        {
            if (e.HasFocus)
            {
                Window.SetSoftInputMode(SoftInput.StateHidden);
                DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime time)
                {
                    (sender as TextInputEditText).Text = time.ToLongDateString();
                });
                frag.Show(FragmentManager, DatePickerFragment.TAG);
            }
            else
                Window.SetSoftInputMode(SoftInput.StateVisible);
        }
    }
}